package com.walter.epay.util;

import cn.hutool.core.util.StrUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 *
 * @author wuchenxi
 * @date 2022-12-31 14:06:33
 */
public class EpayMD5Util {

    private static final char[] HEX_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获取md5加密后的文本
     *
     * @param text 需要加密的文本内容
     * @return
     * @throws NoSuchAlgorithmException 加密异常
     */
    public static String md5(String text) throws NoSuchAlgorithmException {
        if (StrUtil.isEmpty(text)) {
            return text;
        }
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] digest = messageDigest.digest(text.getBytes());

        char[] chars = new char[32];

        for (int i = 0; i < chars.length; i += 2) {
            byte b = digest[i / 2];
            chars[i] = HEX_CHARS[b >>> 4 & 15];
            chars[i + 1] = HEX_CHARS[b & 15];
        }
        return new String(chars);

    }
}
